<template>
  <div class="collectSync">
    <div class="quick-test question-practice">
      <div class="quick-test-banner flex-space-be w1200" style="height: 80px;
                background: #fff;
                border-radius: 12px;
                line-height: 80px;
                text-align: center;
                font-size: 30px;
                font-weight: 400;
                color: #363636;">
        {{ title }}
        <i v-if="haveCollect" @click="readCollect" :class="[defaultStart ? 'el-icon-star-on' : 'el-icon-star-off']"
          style="color: rgb(241, 209, 149); cursor: pointer;"></i>
      </div>
      <el-card v-if="!haveCollect" class="w1200" shadow="never"
        style="border-radius: 12px;text-align: center;padding: 40px 0;">
        <img src="@/assets/img/no-question.png" alt="" />
        <p class="no-text">暂无收藏</p>
      </el-card>
      <div v-if="haveCollect" class="flex-space-be question-practice-container w1200">
        <div class="question-left question-container" style="height: 100%;">
          <div class="question-header flex-space-be" v-if="question">
            <div class="left-type">
              {{ question.answerType == 1 ? "单项选择" : "填空题" }}
            </div>
          </div>
          <div class="question-box question-left-container" v-if="question">
            <Question :question="question" :nowIndex="nowIndex + 1" :isAnswer="question.isAnswer" :classify="5"
              ref="question"></Question>
          </div>
          <div class="btn-box mt20" v-if="question">
            <el-button class="button button-bg-primary" @click="checkStudyQuestion"
              :disabled="question.studentAnswer.length <= 0" v-show="!question.isAnswer" :loading="submitQuestionLoading">
              提交答案
            </el-button>
            <el-button class="button button-bg-primary" @click="nextQuestion" v-show="question.isAnswer"
              :loading="nextQuestionLoading">
              下一题
            </el-button>
          </div>
        </div>
        <div class="question-right" style="height: 100%;">
          <div class="question-right-header">
            <h4>题目序号</h4>
            <p>
              <span class="right">正确</span>
              <span class="wrong">错误</span>
              <span class="checked">选中</span>
            </p>
          </div>
          <div class="question-right-container scrollbar">
            <div class="list-num">
              <div class="list-num-item click" :class="[
                question.isAnswer && question.isTrue ? 'right-item' : '',
                question.isAnswer && !question.isTrue ? 'wrong-item' : '',
                index == nowIndex ? 'checked-item' : '',
              ]" v-for="(question, index) in questionList" :key="index" @click="changeIndex(index)">
                {{ index + 1 }}
              </div>
            </div>
          </div>
        </div>
      </div>
      <!-- <div class="w1200 mt10">
        <el-pagination :style="{ float: 'right' }" @size-change="handleSizeChange" @current-change="handleCurrentChange"
          :current-page.sync="currentPage" :page-size="100" layout="total, prev, pager, next" :total="1000">
        </el-pagination>
      </div> -->
    </div>
    <div @click="openDrawer" class="mosk-btn">题目类型选择</div>
    <el-drawer title="题目类型选择" :visible.sync="drawer" direction="rtl" :wrapperClosable="false" :modal="false"
      :show-close="false">
      <span class="mosk-drawer-close" @click="drawer = false"><i class="el-icon-arrow-right"></i></span>
      <el-form ref="studentForm" :model="syncForm" label-width="80px">
        <!-- 题目来源 -->
        <el-row :gutter="24">
          <el-col :span="22">
            <el-form-item label="题目来源:">
              <el-radio-group v-model="syncForm.source">
                <el-radio-button :label="6">全部</el-radio-button>
                <el-radio-button :label="3">随堂练习</el-radio-button>
                <el-radio-button :label="4">闯关测试</el-radio-button>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 题型 -->
        <el-row :gutter="24">
          <el-col :span="22">
            <el-form-item label="题型:">
              <el-radio-group v-model="syncForm.question_type">
                <el-radio-button :label="null">全部</el-radio-button>
                <el-radio-button :label="0">单项选择</el-radio-button>
                <el-radio-button :label="1">填空题</el-radio-button>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 时间范围 -->
        <el-row :gutter="24">
          <el-col :span="22">
            <el-form-item label="时间范围:">
              <el-date-picker v-model="syncForm.dataTime" value-format="timestamp" type="daterange" align="right"
                unlink-panels range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"
                :picker-options="pickerOptions">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 单元选择 -->
        <el-row :gutter="24">
          <el-col :span="22">
            <el-form-item label="单元选择:">
              <el-select v-model="syncForm.unit_id" placeholder="请选择">
                <el-option v-for="item in elementOptions" :key="item.unit_id" :label="item.unit_name"
                  :value="item.unit_id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-drawer>
  </div>
</template>
<script>
import Question from "@/components/Question";
import { studentCollection, addStudentCollectionQuestion, deleteStudentCollectionQuestion } from "@/api/individuationRead.js"
import { getUnitList } from "@/api/question";
export default {
  data() {
    return {
      defaultStart: true,
      haveCollect: true,
      drawer: false,
      paperData: {},
      syncForm: {
        source: 6,
        // source_type: 6,
        question_type:null,
        unit_id: null,
        dataTime: [],
      },
      // 快捷日期
      pickerOptions: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
      // 单元数据
      elementOptions: [],
      currentPage: 4,
      checkedBookData: {},
      unitId: null,
      isReview: false,
      questionList: [],
      reviewQuestionId: [],
      nowIndex: 0,
      question: null,
      nextQuestionLoading: false,
      submitQuestionLoading: false,
    };
  },
  computed: {
    title() {
      switch (this.syncForm.source) {
        case 6:
          return "全部"
        case 3:
          return "随堂练习"
        case 4:
          return "闯关测试"
        default:
          return "全部"
      }
    }
  },
  watch: {
    syncForm: {
      async handler(nv) {
        this.nowIndex = 0
        let { unit_id, source, dataTime,question_type } = nv
        let start_time, end_time;
        if (dataTime.length) {
          start_time = dataTime[0]
          end_time = dataTime[1]
        } else {
          start_time, end_time = null
        }
        let data = {
          book_id: this.checkedBookData.book_id,
          unit_id,
          question_type,
          article_question_type: source,
          source: source,
          category: null,
          mode:null,
          is_individ: 0,
          end_time,
          start_time
        }
        this.studentCollection(data)
      },
      deep: true
    }
  },
  methods: {
    readCollect() {
      const { id, unit_id } = this.questionList[this.nowIndex]
      console.log(this.questionList[this.nowIndex]);
      let data = {
        unit_id,
        book_id: this.checkedBookData.book_id,
        source_type: null,
        question_type:null,
        link_id: id,
        source: null,
        is_individ: 0
      }
      this.$confirm('此操作将移除收藏并载入下一题, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      }).then(async () => {
        await deleteStudentCollectionQuestion(data)
        this.$message({
          type: 'success',
          message: '删除成功!'
        });
        if (this.questionList.length == this.nowIndex + 1) {
          this.nowIndex -= 1
        }
        let { unit_id, source, question_type, dataTime } = this.syncForm
        let start_time, end_time;
        if (dataTime.length) {
          start_time = dataTime[0]
          end_time = dataTime[1]
        } else {
          start_time, end_time = null
        }
        let testData = {
          book_id: this.checkedBookData.book_id,
          unit_id,
          article_question_type: source,
          source: source,
          question_type,
          category: null,
          mode:null,
          is_individ: 0,
          end_time,
          start_time
        }
        this.studentCollection(testData)
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消操作'
        });
      });

    },
    // 输入题目
    inputAnswer(e, index) {
      this.$set(this.question.studentAnswer, index - 1, e.target.value);
    },
    // 格式化题目
    formatQuestion(testData,id) {
      let question = {
        id,
        unit_id:testData.unit_id,
        parse: testData.parse,
        questionId: testData.question_id,
        title: testData.title,
        initTitle: testData.title,
        inputNum: 0,
        answerType: testData.type == 1 ? 1 : 2,
        answerList: testData.answers.map((answer) => {
          return {
            answer_id: answer.id,
            answer: answer.answer,
            order_index: answer.order_index,
            is_true: answer.is_true
          };
        }),
        isAnswer: false,
        studentAnswer: [],
        startTime: new Date().getTime(),
      };
      if (question.answerType == 2) {
        let index = 1;
        let newTitle = question.title;
        let questionIndex = 1
        let flag = true
        // 原本逻辑
        let pos = newTitle.indexOf("_____");
        while (pos !== -1) {
          flag = false
          newTitle = newTitle.replace(
            /_{5}/,
            ` <input class='question-input' autocomplete="off" id='input-${question.questionId}-${index}' onpaste = "return false";></input> `
          );
          index++;
          pos = newTitle.indexOf("_____");
        }
        if (flag) {
          let posStart = newTitle.indexOf("<u>");
          while (posStart !== -1) {
            newTitle = newTitle.replace(
              /<u>/,
              ` <u class="already_fix"><input class='question-input' autocomplete="off" id='input-${question.questionId}-${questionIndex}' onpaste = "return false";></input> `
            );
            index++;
            posStart = newTitle.indexOf("<u>");
          }
        }
        question.title = newTitle;
        question.inputNum = index - 1;
      }
      this.questionList.push(question);
    },
    initStudentCollection() {
      let data = {
        book_id: this.checkedBookData.book_id,
        unit_id: null,
        article_question_type: 6,
        source: 6,
        category: null,
        mode: null,
        is_individ: 0
      }
      this.studentCollection(data)
    },
    // 获取所有题目
    async studentCollection(data) {
      studentCollection(data).then((res) => {
        this.nextQuestionLoading = false;
        if (res.code == 200) {
          // const testData = res.data[1][1].article_question_answer_info_list[0]
          const resList = [...res.data[0], ...res.data[1]]
          if (resList.length <= 0) {
            this.haveCollect = false
            return
          } else {
            this.haveCollect = true
          }
          this.questionList = []
          resList.forEach(item => this.formatQuestion(item.article_question_answer_info_list[0],item.id))
          this.setQuestion();
        } else if (res.code == 405) {
          this.$alert("暂无试题", "消息提示", {
            confirmButtonText: "确定",
            callback: () => {
              this.goStudyCenter();
            },
          });
        }
      })
        .catch(() => {
          this.nextQuestionLoading = false;
        });
    },
    // 设置题目
    setQuestion() {
      this.question = this.questionList[this.nowIndex];
      this.$nextTick(() => {
        if (this.question.answerType == 2 && !this.question.isAnswer) {
          for (let i = 1; i <= this.question.inputNum; i++) {
            document
              .getElementById(`input-${this.question.questionId}-${i}`)
              .addEventListener("input", (e) => {
                this.inputAnswer(e, i);
              });
          }
        }
      });
    },
    // 下一题
    nextQuestion() {
      let flag = this.nowIndex + 1
      if (flag >= this.questionList.length) {
        this.$confirm('当前为最后一道收藏题目, 是否跳转到第一道?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
        }).then(() => {
          // this.disposepaperData(this.paperDataList[0])
          this.nowIndex = 0
          this.setQuestion();
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          });
        });
        return
      }
      this.nowIndex += 1
      this.setQuestion();
    },
    changeIndex(index) {
      this.nowIndex = index;
      this.setQuestion();
    },
    // 检查题目
    checkStudyQuestion() {
      for (let i = 0; i < this.question.inputNum; i++) {
        if (!this.question.studentAnswer[i]) {
          this.question.studentAnswer[i] = "";
        }
      }
      this.question.title = this.question.initTitle;
      this.question.trueAnswer = this.question.answerList.filter(item => item.is_true == 1)
      this.question.verifyAnswer = []
      if (this.question.answerType == 1) {
        this.question.isTrue = this.question.trueAnswer[0].answer_id == this.question.studentAnswer[0] ? true : false
      }
      if (this.question.answerType == 2) {
        this.question.studentAnswer.forEach((item, index) => {
          if (item.trim() == this.question.answerList[index].answer) {
            this.question.verifyAnswer.push({
              answer: item,
              is_true: 1,
              order: index + 1,
            })
          } else {
            this.question.verifyAnswer.push(
              {
                answer: item,
                is_true: 0,
                order: index + 1,
              }
            )
          }
        })
        if (this.question.verifyAnswer.filter(item => item.is_true == 0).length > 0) {
          this.question.isTrue = false
        } else {
          this.question.isTrue = true
        }
      }
      this.question.isAnswer = true;
      this.$refs.question.showParse = true;
      this.$forceUpdate();
    },
    goStudyCenter() {
      this.$router.push({
        name: "questionStudyCenter",
      });
    },
    async getUnitList() {
      let params = {
        bookId: this.checkedBookData.book_id,
      };
      const { data } = await getUnitList({ params })
      this.elementOptions = data
    },
    openDrawer() {
      this.drawer = true;
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
    },
    handleCurrentChange(val) {
      console.log(`每页 ${val} 条`);
    },
  },
  created() {
    this.checkedBookData = JSON.parse(localStorage.getItem("bookData"));
    this.getUnitList()
    this.initStudentCollection()

  },
  components: {
    Question,
  },
};
</script>
<style lang="scss" scoped>
.collectSync {
  .mosk-btn {
    border-bottom-left-radius: 6px;
    border-top-left-radius: 6px;
    position: fixed;
    top: 40%;
    right: 0;
    font-size: 16px;
    letter-spacing: 4px;
    padding: 10px 5px;
    writing-mode: vertical-rl;
    background: $color-main;
    color: aliceblue;
  }

  /deep/ .el-drawer__wrapper {
    pointer-events: none;
  }

  /deep/ .el-drawer.rtl {
    pointer-events: all;
  }

  /deep/ .el-drawer {
    width: 350px !important;
  }

  .el-drawer__body {
    position: relative;
    top: 0;
    left: 0;

    .mosk-drawer-close {
      position: absolute;
      top: 50%;
      left: 0;
      transform: translateY(-50%);
      font-size: 30px;
      padding: 8px 0;
      background: rgb(189, 188, 188);
      color: #f1f0f0;
    }
  }

  /deep/ .el-radio-button__inner {
    padding: 6px 5px !important;
  }

  /deep/ .el-input__inner {
    width: 200px;
    height: 30px;
    line-height: 30px;
    padding: 3px 5px;
  }

  /deep/ .el-date-editor .el-range-separator {
    line-height: 22px;
  }

  /deep/ .el-date-editor .el-range__icon {
    line-height: 22px;
  }

  /deep/ .el-input__icon {
    display: none;
  }
}
</style>
